﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SQLite;

namespace DataAccess {
  /// <summary>
  /// Helper object for Data Access Layer
  /// </summary>
  public static class DataHelper {

    /// <summary>
    /// Gets the connection string.
    /// </summary>
    /// <returns></returns>
    public static String GetConnectionString( ) {
      if ( ConfigurationManager.ConnectionStrings.Count == 0 ) {
        throw new InvalidOperationException( "No ConnectionStrings found in .config" );
      }

      ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings[ "SqLiteConnection" ];
      if ( setting == null ) {
        throw new InvalidOperationException( "ConnectionString : SqLiteConnection"  + " not found." );
      }
      return setting.ConnectionString;
    }

    /// <summary>
    /// Creates the connection.
    /// </summary>
    /// <returns></returns>
    public static SQLiteConnection CreateConnection(  ) {
      SQLiteConnection conn = new SQLiteConnection( GetConnectionString( ) );
      conn.Open( );
      return conn;
    }

    /// <summary>
    /// Creates the select after insert command.
    /// </summary>
    /// <param name="connection">The connection.</param>
    /// <param name="tableName">Name of the table.</param>
    /// <returns></returns>
    public static SQLiteCommand CreateSelectAfterInsertCommand( SQLiteConnection connection, string tableName ) {
      SQLiteCommand command = connection.CreateCommand( );
      command.CommandText = "SELECT ID FROM " + tableName + " WHERE ID = last_insert_rowid()";
      return command;
    }

  }
}
